#include "surbasic/BenchmarkBlock.h"
#include "surbasic/surbasic.h"
#include "surbasic/FileInfo.h"

namespace SDBasic {

BenchmarkBlock::BenchmarkBlock(const std::string& name, size_t size)
    : name_(name),
      size_(static_cast<double>(size)),
      start_(time::Timestamp::Now()),
      seconds_(0),
      stopped_(false) {}

void BenchmarkBlock::Start() {
  start_ = time::Timestamp::Now();
  log_callback(LogDebug, "BENCH: Start %s\n", name_.c_str());
  ::fflush(stderr);
  ::fflush(stdout);
}

void BenchmarkBlock::set_size_by_path(const std::string& path) {
  FileInfo::FileStatus s = FileInfo::StatFile(path);
  if (s.type == FileInfo::NotExisted || s.type == FileInfo::Error) set_size(0);

  set_size(s.size);
}

void BenchmarkBlock::Stop() {
  assert(!stopped_);
  stopped_ = true;
  seconds_ = time::TimeDiffInSeconds(time::Timestamp::Now(), start_);
  if (seconds_ <= 0.0) seconds_ = 0.0001;

  log_callback(LogDebug, "BENCH: Done %s @ %.2lf Kb, %.2lf s, %.2lf kB/s\n",
               name_.c_str(), size_kb(), seconds(), speed_kBs());
  ::fflush(stderr);
  ::fflush(stdout);
}

BenchmarkBlock::~BenchmarkBlock() {
  if (stopped_) return;

  stopped_ = true;
  seconds_ = time::TimeDiffInSeconds(time::Timestamp::Now(), start_);
  if (seconds_ <= 0.0) seconds_ = 0.0001;

  log_callback(LogDebug, "BENCH: Failed %s @ %.2lf Kb, %.2lf s\n",
               name_.c_str(), size_kb(), seconds());
  ::fflush(stderr);
  ::fflush(stdout);
}
}
